package com.example.a2207_zh.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2207_zh.R
import com.example.a2207_zh.databinding.ActivityLoginBinding
import com.example.a2207_zh.mvvm.BaseActivity
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    @Autowired
    @JvmField
    var username:String = ""
    @Autowired
    @JvmField
    var password = ""
    override fun getLayout(): Int = R.layout.activity_login

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java
    override fun initView() {
        ARouter.getInstance().inject(this)
        binding.etName.setText(username)
        binding.etPwd.setText(password)
        binding.btnLogin.setOnClickListener {
            val username = binding.etName.text.toString()
            val password = binding.etPwd.text.toString()
            if(username.length!=11){
                ToastUtils.showLong("用户名应为手机号")
                return@setOnClickListener
            }
            if(password.length>8||password.length<6){
                ToastUtils.showLong("密码格式不正确，应为6-8位的字符串")
                return@setOnClickListener
            }
            viewModel.login(username,password)
        }
        binding.goReg.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }
    }

    override fun initData() {
        viewModel.success.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }
        }
        viewModel.fail.observe(this){
            ToastUtils.showLong(it)
        }
    }

}